package kiwi.assist.dev.guieditor.mediator {
	import flash.events.MouseEvent;

	import kiwi.assist.dev.guieditor.model.GUIEditorConfig;
	import kiwi.assist.dev.guieditor.model.UiDetailVO;

	import fl.core.UIComponent;

	import kiwi.assist.dev.guieditor.event.GUIOperateEvent;
	import kiwi.assist.dev.guieditor.view.CanvasView;
	import kiwi.assist.dev.util.SkinComponentAdapter;
	import kiwi.input.InputKey;

	import org.robotlegs.mvcs.Mediator;

	import flash.display.DisplayObject;
	import flash.events.Event;
	import flash.events.KeyboardEvent;

	/**
	 * 画布的中介
	 * @author zhangming.luo
	 */
	public class CanvasMediator extends Mediator {
		[Inject]
		public var view : CanvasView;
		[Inject]
		public var detail : UiDetailVO;
		[Inject]
		public var config : GUIEditorConfig;

		override public function onRegister() : void {
			super.onRegister();
			addViewListener(Event.ADDED, handleAdded);
			addViewListener(KeyboardEvent.KEY_DOWN, onKeyDown);
			addViewListener(KeyboardEvent.KEY_UP, onKeyUp);
			addViewListener(MouseEvent.CLICK, onClick);
		}

		private function onKeyDown(e : KeyboardEvent) : void {
			var ui : DisplayObject = detail.currentEditUi;
			if (!ui) {
				return;
			}
			if (e.keyCode == InputKey.LEFT.keyCode) {
				ui.x -= 1 * (e.shiftKey ? 10 : 1);
			} else if (e.keyCode == InputKey.RIGHT.keyCode) {
				ui.x += 1 * (e.shiftKey ? 10 : 1);
			} else if (e.keyCode == InputKey.UP.keyCode) {
				ui.y -= 1 * (e.shiftKey ? 10 : 1);
			} else if (e.keyCode == InputKey.DOWN.keyCode) {
				ui.y += 1 * (e.shiftKey ? 10 : 1);
			}
		}

		private function onClick(e : MouseEvent) : void {
			view.stage.focus = view;
		}

		private function onKeyUp(e : KeyboardEvent) : void {
			var ui : DisplayObject = detail.currentEditUi;
			if (!ui) {
				return;
			}
			if (e.keyCode == InputKey.DELETE.keyCode) {
				if (ui.parent.parent != view) {
					// 不属于我的
					return;
				}
				if (ui is SkinComponentAdapter) {
					dispatch(new GUIOperateEvent(GUIOperateEvent.BACKGROUND_REMOVE, ui));
				} else {
					dispatch(new GUIOperateEvent(GUIOperateEvent.UI_REMOVE, ui));
				}
			}
		}

		private function handleAdded(e : Event) : void {
			// 为每个添加的对象增加选中和调整==相关的方法
			// 不采用直接注册的方式是因为不好界定那些是控件(因为UIComponent内可能有UIComponent)
			if (!(e.target is UIComponent)) {
				return;
			}
			var target : UIComponent = UIComponent(e.target);
			var tmp : DisplayObject = target;
			do {
				if (mediatorMap.hasMediatorForView(tmp)) {
					return;
				}
				tmp = tmp.parent;
			} while (tmp != view);
			// 手工产生一个新的mediator
			var mediator : EditableUiMediator = new EditableUiMediator();
			mediator.eventDispatcher = eventDispatcher;
			mediator.contextView = contextView;
			mediator.mediatorMap = mediatorMap;
			mediator.config = config;
			mediatorMap.registerMediator(e.target, mediator);
		}
	}
}
